package ace.cmp.security.oauth2.resource.server.core.web;

import ace.cmp.core.model.R;
import ace.cmp.json.api.JsonService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * @author caspar
 * @date 2023/3/14 17:15
 */
public class ResourceServerAuthenticationEntryPoint implements AuthenticationEntryPoint {
  private final JsonService jsonService;

  public ResourceServerAuthenticationEntryPoint(JsonService jsonService) {
    this.jsonService = jsonService;
  }

  @Override
  public void commence(
      HttpServletRequest request,
      HttpServletResponse response,
      AuthenticationException authException)
      throws IOException, ServletException {

    R<String> result =
        R.<String>builder()
            .message("登录信息已过期,请重新登录.")
            .data(authException != null ? authException.getMessage() : "")
            .code(HttpStatus.UNAUTHORIZED.value())
            .build();

    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    PrintWriter printWriter = response.getWriter();
    printWriter.append(jsonService.toJson(result));
  }
}
